<template>
    <div class="container">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px" class="demo-ruleForm">
            <div class="container">
                <el-steps :active="active" finish-status="success">
                    <el-step title="选择原料" ></el-step>
                    <el-step title="加工"></el-step>
                    <el-step title="成品信息"></el-step>
                </el-steps> 
            </div>
			<div class="conntainer" v-if="this.active == 0">
				<el-row class="container" style="margin-top:20px;">
			
					 <el-table
					:data="tableData"
					border
					style="margin-top:20px;"
					ref="multipleTable"
					header-cell-class-name="table-header"
				>
					<el-table-column prop="breedName" sortable label="品名"></el-table-column>
					<el-table-column prop="batch" sortable label="批号"></el-table-column>
					<el-table-column prop="source" sortable label="来源"></el-table-column>
					<el-table-column prop="place" sortable label="地块/供应商"></el-table-column>
					<el-table-column prop="number" sortable label="数量">
						<template slot-scope="scope">
							<el-input v-model="scope.row.number" style="width:200px;"></el-input>
							<span style="margin-left:10px;">{{scope.row.units}}</span>
							
						</template>
					</el-table-column>
					<el-table-column label="操作" width="150" align="center">
						<template slot-scope="scope">
							<el-button
								type="text"
								@click="handleDel(scope.$index, scope.row)"
							>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				
				<div @click="addManure" class="addManure">添加原料</div>
			</el-row>
			</div>
			<div class="container" v-if="this.active == 1" style="margin-top:20px;">
				<el-form-item label="选择工艺工序：">
				    <el-select v-model="productName"  @change="getflow" value-key="id" filterable placeholder="请选择" style="width: 300px;">
						<el-option
							v-for="item in processList"
							:key="item.id"
							:label="item.name"
							:value="item"
						>
						{{item.name}}
						</el-option>
					</el-select>
				</el-form-item>
			</div>
            
			<div class="container" style="margin-top:20px;" v-if="this.active == 1">
				<h3>工艺工序</h3>
				<div style="height:500px;margin-top:20px;">
					<el-col :span ="7" style="height:500px;">
						<el-steps direction="vertical" :active="activeTechnologies">
							<el-step v-for ="(item,index) in technologies" :key="index" :title="item.name" @click.native="switchTable(index)"></el-step>
							
						</el-steps>
					</el-col>
					 <el-col :span ="14"  v-for ="(item,index) in technologyList" :key="index" v-if="switchTableIndex == index">
						  <el-form-item label="开始时间：" >
						      <el-date-picker
						          v-model="item.beginTime"
						          type="date"
						          value-format="yyyy-MM-dd"
						          placeholder
						          style="width:300px"
						      ></el-date-picker> 
						  </el-form-item>
						  <el-form-item label="结束时间：">
						      <el-date-picker
						          v-model="item.endTime"
						          type="date"
						          value-format="yyyy-MM-dd"
						          placeholder
						          style="width:300px"
						      ></el-date-picker> 
						  </el-form-item>
						  <el-form-item label="视频监控：">
							  <el-select v-model="item.equipmentName" value-key="id" placeholder="请选择" @change="getfacilityDetails" style="width:300px">
							      <el-option
							        v-for="item in facilityList"
							        :key="item.id"
							        :label="item.name"
							        :value="item">
							      </el-option>
							    </el-select>
								<!-- <el-input placeholder="请输入内容"  v-model="technologyList[0].equipmentName" style="width:300px">
								</el-input> -->
						  </el-form-item>
						  <el-form-item label="负责人：">
								<el-input placeholder="请输入内容"  v-model="item.userName" style="width:300px">
								</el-input>
						  </el-form-item>
						  <el-form-item label="操作照片：">
							  <div @click="handelsuccess(index)">
							  	<el-upload
							      class="upload-poster"                               
							      action="https://jsonplaceholder.typicode.com/posts/"
							      :show-file-list="false"
							      :on-change="imgPreview"
							      :auto-upload="false">
							      <img v-if="item.processImgs" :src="item.processImgs" class="avatar">
							      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
							  </el-upload>
							  jpg、png、gif格式，60x60像素，不超过2MB
							  </div>
						  </el-form-item>
						 
					  </el-col>
				</div>
			</div>
			
			<div class="conntainer" v-if="this.active == 2">
				<el-row class="container" style="margin-top:20px;">
					 <el-table
					:data="finishedProductList"
					border
					style="margin-top:20px;"
					ref="multipleTable"
					header-cell-class-name="table-header"
				>
					<el-table-column prop="productName" sortable label="品名"></el-table-column>
					<el-table-column prop="batch" sortable label="加工批号">
						<template slot-scope="scope">
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.batch" >
							   
							  </el-input>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="grade" sortable label="品级">
						<template slot-scope="scope">
							<el-select v-model="scope.row.grade"  value-key="name"  filterable placeholder="请选择">
							    <el-option
							        v-for="item in pj"
							        :key="item.name"
							        :label="item.name"
							        :value="item.name"
							    >
							    {{item.name}}
							    </el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column prop="totalNumber" sortable label="成品数量">
						<template slot-scope="scope">
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.totalNumber" @change="count(scope.$index, scope.row)" style="width:200px;">
							   
							  </el-input>
							  <span style="margin-left:10px;">{{scope.row.units}}</span>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="title" sortable label="关联产品介绍" >
						<template slot-scope="scope" >
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.title" @click.native="relevance(scope.$index, scope.row)" >
							   
							  </el-input>
							</div>
						</template>
					</el-table-column>

					<el-table-column label="操作" width="150" align="center">
						<template slot-scope="scope">
							<el-button
								type="text"
								@click="handleCheck(scope.$index, scope.row)"
							>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-row>
			</div>
     
            
            <el-form-item class="footerFixed" label-width="0px">
				<el-button @click="prev" v-if="active == 1 || active == 2">上一步</el-button>
                <el-button type="primary" @click="next" v-if="active == 0 || active == 1">下一步</el-button>
                <el-button v-if="active == 2" type="primary" @click="submitrule('ruleForm')">提交</el-button>
            </el-form-item>
        </el-form>
		<el-dialog title="选择原料" :visible.sync="dialogTableVisible">	
			<el-form>
				<el-row :span="24">
					<el-col :span ="8">
						<el-form-item label="来源：">
							<el-select v-model="source" placeholder="请选择" style="width:auto;" @change="get">
								<el-option label="基地采收" value="基地采收"></el-option>
								<el-option label="采购入库" value="采购入库"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span ="8">
						<el-form-item label="品名：">
							<el-select v-model="reapName" placeholder="请选择" @change="breednameSearch">
							    <el-option
							      v-for="item in breedNameList"
							      :key="item"
							      :label="item"
							      :value="item">
							    </el-option>
							  </el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :span ="8" v-if="source == '基地采收'">
						<el-form-item label="所属地块：">
							<el-select v-model="soilName" placeholder="请选择" style="width:auto;" @change="get">
								<el-option label="基地采收" value="基地采收"></el-option>
								<el-option label="采购入库" value="采购入库"></el-option>
							</el-select>
						</el-form-item>
					</el-col> -->
				</el-row>
				
				
			</el-form>
		  <el-table
		  v-if="ifshow"
		        :data="materialList"
		        border
		        style="margin-top:20px;"
		        ref="multipleTable"
		        header-cell-class-name="table-header"
		    >
		        <el-table-column prop="reapName" sortable label="品名"></el-table-column>
		        <el-table-column v-if="source == '基地采收'" prop="soilName" sortable label="所属地块"></el-table-column>
				<el-table-column v-else prop="phone" sortable label="供应商"></el-table-column>
		        <el-table-column prop="batch" sortable label="批号"></el-table-column>
		        <el-table-column prop="surplusNumber" sortable label="可用数量">
					<template slot-scope="scope">
						{{scope.row.surplusNumber}}{{scope.row.units}}
					</template>
				</el-table-column>
		        <el-table-column label="操作" width="150" align="center">
		            <template slot-scope="scope">
		                <el-button
		                    type="text"    
		                    @click="handleSelect(scope.$index, scope.row)"
		                >选择</el-button>
		            </template>
		        </el-table-column>
		    </el-table>
			<el-table
			v-if="ifshow1"
			      :data="materialList"
			      border
			      style="margin-top:20px;"
			      ref="multipleTable"
			      header-cell-class-name="table-header"
			  >
			      <el-table-column prop="productName" sortable label="品名"></el-table-column>
			      <el-table-column v-if="source == '基地采收'" prop="soilName" sortable label="所属地块"></el-table-column>
							<el-table-column v-else prop="supplierName" sortable label="供应商"></el-table-column>
			      <el-table-column prop="storageBatch" sortable label="批号"></el-table-column>
			      <el-table-column prop="surplus" sortable label="可用数量">
					  <template slot-scope="scope">
						  {{scope.row.subtotal}}{{scope.row.unit}}
					  </template>
				  </el-table-column>
			      <el-table-column label="操作" width="150" align="center">
			          <template slot-scope="scope">
			              <el-button
			                  type="text"    
			                  @click="handleSelect(scope.$index, scope.row)"
			              >选择</el-button>
			          </template>
			      </el-table-column>
			  </el-table>
			 <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage" :total="total"  @current-change="handleCurrentChange" style="margin-top:20px"></el-pagination>
		</el-dialog>
		
		<el-dialog title="选择产品介绍" :visible.sync="dialogTableVisible1">
			<el-table
			    :data="tableData1"
			    border
			    style="margin-top:20px;"
			    ref="multipleTable"
			    header-cell-class-name="table-header"
			>
				<el-table-column prop="img" sortable label="产品图">
					<template slot-scope="scope">
						<img :src="$store.state.imageUrls + scope.row.img" alt="" style="width:50px; height:50px;" v-if="scope.row.img != '' || scope.row.img!= null ">
					</template>
				</el-table-column>
			    <el-table-column prop="title" sortable label="产品标题"></el-table-column>
			    <!-- <el-table-column prop="createTime" sortable label="添加时间"></el-table-column> -->
			    <el-table-column prop="relatedProducts" sortable label="关联产品"></el-table-column>
				<el-table-column prop="quality" sortable label="保质期"></el-table-column>
			    <el-table-column label="操作" width="150" align="center">
			        <template slot-scope="scope">
			            <el-button
			                type="text"
			                @click="handleSelectProductDetails(scope.$index, scope.row)"
			            >选择</el-button>
			            
			        </template>
			    </el-table-column>
			</el-table>
			<el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage1"  @current-change="handleCurrentChange1" :total="total1" style="margin-top:20px"></el-pagination>
		  
		</el-dialog>
    </div>
</template>

<script>
	import {technology_findByAll,technology_findById,reapdetail_findByList,reapDetail_findAllBreed,facility_findByAll,base_findByAll,products_findByAll,products_findByList,process_save,storage_findByList} from "@/request/api"
    export default {
        data(){
            return{
				ifshow:true,
				ifshow1:false,
				pj:[
					{name:'一级'},
					{name:'二级'},
					{name:'三级'}
				],
				finishedProductList:[],
				dialogTableVisible1:false,
				activeTechnologies:0,
				breedNameList:[],
				materialList:[],
				reapName:'',
				soilName:'',
				technologies:[],
				processList:[],
				res:{
					images:[]
				},
				productName:'',
				headImg:{},
				tableData:[],
				source:"基地采收",
				dialogTableVisible:false,
                total:0,
                currentPage:1,
				currentPage1:1,
				total1:1,
				tableData1:[],
                pagesize:10,
                active:0,
                rules:{},
                ruleForm:{},
                labelPosition:"right",
				switchTableIndex:0,
				technologyList:[
					
				],
				facilityList:[],
				technologyId:'',
				methodName:'',
				methodId:'',
				index:'',
				xindex:''
            }
        },
        mounted(){
			this.init()
			this.selectMaterial()
			this.selectBreedName()
			this.getfacility()
			this.getSelectBase()
			this.getProductDetails()
        },
        methods:{
			// 计算 成品数量
			count(index,row){
				if(this.tableData[index].number<this.finishedProductList[index].totalNumber){
					this.$notify({
					    title: '提示',
					    message: '成品总量不等大于投入总量',
					    type: 'info',
					    duration:1000
					});
					row.totalNumber = ""
				}
			},
			// 获取 选择 产品介绍 的列表
			getProductDetails(){
				let data = {
					page:this.currentPage1
				}
				products_findByList(data).then((res)=>{
					this.tableData1 = res.rows
					this.total1 = res.total
				})
			},
			
			// 获取地块下拉   有问题 待修改
			getSelectBase(){
				base_findByAll("").then((res)=>{
					
				})
			},
			//获取 图片的 index
			handelsuccess(index){
				this.index = index
			},
			// 获取设备名和id
			getfacilityDetails(ele){
				this.technologyList[this.switchTableIndex].equipmentName = ele.name
				this.technologyList[this.switchTableIndex].equipmentId = ele.id
			},
			// 获取设备下拉
			getfacility(){
				facility_findByAll("").then((res)=>{
					 this.facilityList = res.data
				})
			},
			
			// 点击切换工艺的步骤
			switchTable(index){
				this.technologyList[this.switchTableIndex+1].methodName = this.technologies[index].name
				this.technologyList[this.switchTableIndex+1].methodId = this.technologies[index].id
				this.switchTableIndex = index
				this.activeTechnologies = index
			},
			
			// 采购入库
			selectPurchase(){
				let data = {
					page:this.currentPage,
					source:'采购入库'
				}
				storage_findByList(data).then((res)=>{
					this.materialList = res.rows
					this.total = res.total
					for(var i=0;i<this.materialList.length;i++){
						
						var st = this.materialList[i].unit.substr(this.materialList[i].unit.lastIndexOf('/', this.materialList[i].unit.lastIndexOf('/') - 1) + 1);
						var str = st.lastIndexOf("\/")
						this.materialList[i].units = st.substring(0,str)
					}
				})
			},
			// 判断是采购入库 还是 基地采收
			get(ele){
				this.reapName = ""
				this.soilName = ""
				this.currentPage = 1
				if(ele == "基地采收"){
					this.selectMaterial()
					this.ifshow = true
					this.ifshow1 = false
				}else{
					this.selectPurchase()
					this.ifshow = false
					this.ifshow1 = true
				}
			},
			// 删除选择的原料
			handleDel(index,row){
				this.tableData.splice(index,1)
			},
			//  获得工艺具体的步骤
			getflow(ele){
				var id = ele.id
				this.technologyId = ele.id
				this.technology = ele.name
				this.technologyList = []
				technology_findById(id).then((res)=>{
					var name = localStorage.getItem("ms_username")
					var id = localStorage.getItem("ms_id")
					this.technologies = res.data.technologies
					for(var i=0;i<this.technologies.length;i++){
						this.technologyList.push({
							technologyId:this.technologyId,
							methodId:"",
							methodName:"",
							beginTime:'',
							endTime:'',
							userId:id,
							userName:name,
							equipmentId:'',
							equipmentName:'',
							processImg:'',
							processImgs:'',
							files:''
						})
					}
					this.technologyList[0].methodName = this.technologies[0].name
					this.technologyList[0].methodId = this.technologies[0].id
				})
			},
			// 工艺列表
			init(){
				technology_findByAll("").then((res)=>{
					this.processList = res.data
				})
				
			},
			
			// 当选择基地采收时的   原料列表
			selectMaterial(){
				let data = {
					page:this.currentPage,
					reapName:this.reapName,
					soilName:this.soilName
				}
				reapdetail_findByList(data).then((res)=>{
					this.materialList = res.rows
					this.total = res.total
				})
			},
			//选择原料时  品名的下拉
			selectBreedName(){
				reapDetail_findAllBreed("").then((res)=>{
					this.breedNameList = res.data
				})
				reapDetail_findAllBreed
			},
			//根据品名 进行搜索
			breednameSearch(ele){
				this.reapName = ele
				this.selectMaterial()
			},
			// 选择原料
			handleSelect(index,row){
				if(this.source == "基地采收"){
					this.tableData.push({
						breedId:row.id,
						breedName:row.reapName,
						batch:row.batch,
						source:this.source,
						type:this.source,
						place:row.soilName,
						number:row.surplusNumber,
						units:row.units,
						id:row.reapId
					})
					this.dialogTableVisible = false
				}else{
					this.tableData.push({
						breedId:row.id,
						source:this.source,
						type:this.source,
						breedName:row.productName,
						number:row.subtotal,
						units:row.units,
						place:row.supplierName,
						batch:row.storageBatch
					})
					this.dialogTableVisible = false
				}
				
			},
			// 选择 产品介绍 添加到列表中
			handleSelectProductDetails(index,row){
				this.finishedProductList[this.xindex].productId = row.id
				this.finishedProductList[this.xindex].title = row.title
				this.dialogTableVisible1 = false
			},
			//上传图片
			imgPreview(file,fileList) {
				this.technologyList[this.index].processImgs =  URL.createObjectURL(file.raw);
			    this.headImg =  URL.createObjectURL(file.raw);
			    let fileName = file.name;
			    let regex = /(.jpg|.gif|.png)$/;
			    if (regex.test(fileName.toLowerCase())) {
					this.technologyList[this.index].files = file.raw
					this.technologyList[this.index].processImg = file.name
			    } else {
			        this.$message.error('请选择图片文件');
			    }
			    
			},
			// 点击  添加  打开弹窗
			addProductDetails(){
				
			},
			
			// 点击 添加原料打开弹窗
			addManure(){
			    this.dialogTableVisible = true
			},
			relevance(index,row){
				this.xindex = index
				this.dialogTableVisible1 = true
			},
			// 点击下一步时 判断 原料是否为空   工艺是否为空
            next(){
				if(this.active == 0){
					if(this.tableData == "" || this.tableData == null || this.tableData == undefined){
						this.$notify({
						    title: '提示',
						    message: '原料不能为空',
						    type: 'info',
						    duration:1000
						});
					}else{
						var arr = 0
						for(var i=0;i<this.tableData.length;i++){
							arr = arr + Number(this.tableData[i].number)
						}
						this.number = arr
						this.nextStep()
					}
				}else if (this.active == 1){
					if(this.productName == ""){
						this.$notify({
						    title: '提示',
						    message: '工艺不能为空',
						    type: 'info',
						    duration:1000
						});
						// this.dialogTableVisible1 = false
					}else{
						for(var i=0;i<this.tableData.length;i++){
							this.finishedProductList.push({
								technologyId:this.technologyId,
								technology:this.technology,
								productName:this.tableData[i].breedName,
								batch:'',
								grade:'',
								totalNumber:'',
								surplusNumber:'',
								units:this.tableData[i].units,
								productId:'',
								title:'',
							})
						}
						this.nextStep()
					}
				}
               
            },
			//下一步
			nextStep(){
				if (this.active++ > 0) {
							
				}
			},
			handleCurrentChange1(val){
			    this.currentPage1 = val
			   this.getProductDetails()
			},
			
			//选择添加原料弹窗列表的分页
            handleCurrentChange(val){
                this.currentPage = val
                this.selectMaterial()
            },
			// 上一步
            prev(){
               --this.active    
               if(this.active<0)this.active = 0 
			   this.finishedProductList = []
			   
            },
			// 提交
            submitrule(){
				this.$confirm('确定要加工吗请谨慎操作', '提示', {
				    confirmButtonText: '确定',
				    cancelButtonText: '取消',
				    type: 'warning'
				}).then(() => {
					let formdata = new FormData
					for(var i=0;i<this.technologyList.length;i++){
					    if(this.technologyList[i].files != "" && this.technologyList[i].files != null){
					        formdata.append("files",this.technologyList[i].files)
					    }
					}
					this.ruleForm.reapId = this.tableData[0].breedId
					this.ruleForm.source = this.source
					this.ruleForm.pmList = JSON.stringify(this.tableData)
					this.ruleForm.pdList =JSON.stringify(this.finishedProductList)
					this.ruleForm.ptList = JSON.stringify(this.technologyList)
					for(var a in this.ruleForm){
					    if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
					        this.ruleForm[a] = ""
					        formdata.append(a,'') 
					    }else{
					        formdata.append(a,this.ruleForm[a])
					    }
						
					}
					process_save(formdata).then((res)=>{
							this.$notify({
						    title: '提示',
						    message: '收获成功',
						    type: 'success',
						    duration:1000
						});
						this.$router.go(-1)
					})
				 //    reap_save(formdata).then((res)=>{
					
					// })
				})
            }
        }
    }
</script>

<style scoped>
    .el-pagination{
        text-align: center;
    }
	.addManure{
	    border-radius:8px;
	    margin-top:20px;
	    width:100%;
	    height:60px;
	    line-height:60px;
	    text-align: center;
	    font-size:16px;
	    background:#EBF5FF 100%;
	}
	.avatar-uploader .el-upload {
	   border: 1px dashed #d9d9d9;
	   border-radius: 6px;
	   cursor: pointer;
	   position: relative;
	   width:180px;
	   overflow: hidden;
	 }
	 
	 .avatar-uploader .el-upload:hover {
	   border-color: #409EFF;
	 }
	
	 .avatar-uploader-icon {
	   font-size: 28px;
	   color: #8c939d;
	   width: 178px;
	   height: 178px;
	   line-height: 178px;
	   text-align: center;
	 }
	 .avatar {
	   width: 178px;
	   height: 178px;
	   display: block;
	 }
	 .addManure{
	     border-radius:8px;
	     margin-top:20px;
	     width:100%;
	     height:60px;
	     line-height:60px;
	     text-align: center;
	     font-size:16px;
	     background:#EBF5FF 100%;
	 }
</style>